package com.leizi.igym.controller.user;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leizi.igym.constant.CourseConstant;
import com.leizi.igym.domain.Plan;
import com.leizi.igym.domain.Post;
import com.leizi.igym.dto.*;
import com.leizi.igym.enums.ReturnCodeEnum;
import com.leizi.igym.exception.BusinessException;
import com.leizi.igym.manager.CosManager;
import com.leizi.igym.resp.Result;
import com.leizi.igym.service.CourseService;
import com.leizi.igym.service.PlanService;
import com.leizi.igym.service.PostService;
import com.leizi.igym.utils.ThrowUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;

/**
 * @Author: leizi0110
 * @CreateTime: 2024-04-05  17:48
 * @Description:
 */

@RestController("userPlanController")
@RequestMapping("/user/plan")
@Tag(name = "用户端-计划相关接口")
@Slf4j
public class PlanController {

    @Resource
    private CourseService courseService;

    @Resource
    private PlanService planService;

    @Operation(summary = "用户端：新增计划")
    @PostMapping
    public Result add(@RequestBody PlanAddDTO dto) {
        log.info("用户端正在添加计划信息，计划信息为：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);
        boolean result = planService.save(dto);

        if (!result) {
            throw new BusinessException(ReturnCodeEnum.OPERATION_ERROR, "添加计划失败！");
        }
        return Result.ok(result);
    }

    @Operation(summary = "用户端：删除计划信息")
    @DeleteMapping("{id}")
    public Result delete(@PathVariable("id") Long id) {
        log.info("用户端正在删除计划信息，计划id为：{}", id);
        ThrowUtils.throwIf(Objects.isNull(id) || id <= 0, ReturnCodeEnum.PARAMS_ERROR);
        boolean result = planService.delete(id);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "删除教练信息失败！");
        }
        return Result.ok(result);
    }

    // @Operation(summary = "用户端：批量删除计划信息")
    // @DeleteMapping("batch")
    // public Result deleteBatch(@RequestBody List<Long> ids) {
    //     log.info("用户端正在批量删除计划信息，计划们的id为：{}", ids);
    //     ThrowUtils.throwIf(CollectionUtil.isEmpty(ids), ReturnCodeEnum.PARAMS_ERROR);
    //     boolean result = courseService.deleteTrainerBatchInAdmin(ids);
    //     if (!result) {
    //         throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "删除教练信息失败！");
    //     }
    //     return Result.ok(result);
    // }

    @Operation(summary = "用户端：修改计划信息")
    @PutMapping("{id}")
    public Result update(@PathVariable("id") Long id, @RequestBody PlanDTO dto) {
        log.info("用户端正在修改计划信息，id为：{}，修改计划为：{}", id, dto);
        ThrowUtils.throwIf(Objects.isNull(dto) ||
                        id == null ||
                        id <= 0 ||
                        !id.equals(dto.getId()),
                ReturnCodeEnum.PARAMS_ERROR);
        boolean result = planService.update(dto);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "修改教练信息失败！");
        }
        return Result.ok(result);
    }


    @Operation(summary = "用户端：根据id查询计划信息")
    @GetMapping("{id}")
    public Result<Plan> getById(@PathVariable("id") Long id) {
        log.info("用户端正在根据id查询计划信息，id为：{}", id);
        ThrowUtils.throwIf(Objects.isNull(id) || id <= 0,
                ReturnCodeEnum.PARAMS_ERROR);

        Plan plan = planService.getPlanById(id);
        if (Objects.isNull(plan)) {
            throw new BusinessException(ReturnCodeEnum.NOT_FOUND_ERROR, "该计划不存在！");
        }
        return Result.ok(plan);
    }

    @Operation(summary = "用户端：修改计划状态")
    @PutMapping("/{id}/{status}")
    public Result<Boolean> complete(@PathVariable("id") Long id,
                                    @PathVariable("status") Integer status) {
        log.info("用户端正在修改计划状态，计划id：{}", id);

        // 校验参数id是否合法
        ThrowUtils.throwIf(Objects.isNull(id) || id < 0, ReturnCodeEnum.PARAMS_ERROR, "计划id有误！");

        // 校验isIdentify参数是否合法
        ThrowUtils.throwIf(Objects.isNull(status) ||
                        !CourseConstant.COURSE_STATUS_LIST.contains(status)
                , ReturnCodeEnum.PARAMS_ERROR, "认证参数有误！");
        boolean result = planService.changeStatus(id, status);
        return Result.ok(result);
    }

    @Operation(summary = "用户端：根据用户id查询计划信息")
    @GetMapping("/user/{userId}")
    public Result<List<Plan>> getByUserId(@PathVariable("userId") Long userId) {
        log.info("用户端正在查询自己所有计划信息，用户id为：{}", userId);
        ThrowUtils.throwIf(Objects.isNull(userId) || userId <= 0,
                ReturnCodeEnum.PARAMS_ERROR);

        List<Plan> planList = planService.getPlanByUserId(userId);
        if (CollectionUtil.isEmpty(planList)) {
            return Result.ok(planList);
        }
        return Result.ok(planList);
    }

    @Operation(summary = "用户端：全文搜索计划")
    @GetMapping("search")
    public Result<List<Plan>> searchPlan(PlanSearchDTO dto) throws IOException {
        log.info("用户端正在全文查询自己计划信息，搜索文本为：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto),
                ReturnCodeEnum.PARAMS_ERROR);
        List<Plan> planList = planService.searchFromES(dto);
        return Result.ok(planList);
    }

    @Operation(summary = "用户端：我的计划数量")
    @GetMapping("myCount")
    public Result myPlanCount(@RequestParam("userId") Long userId) {
        log.info("用户端正在查询自己计划的条数，查询用户id为：{}", userId);
        ThrowUtils.throwIf(Objects.isNull(userId),
                ReturnCodeEnum.PARAMS_ERROR);
        QueryWrapper<Plan> qw = new QueryWrapper<>();
        qw.eq("user_id",userId);
        qw.eq("deleted",0);
        long count = planService.count(qw);
        return Result.ok(count);
    }
}
